<template>
  <a-modal
    :visible="visible"
    :title="formData.userId ? '编辑用户' : '新增用户'"
    :confirm-loading="confirmLoading"
    @cancel="handleCancel"
    @ok="handleOk"
    width="600px"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item label="用户名" name="userName">
        <a-input v-model:value="form.userName" placeholder="请输入用户名" />
      </a-form-item>
      
      <a-form-item label="昵称" name="nickName">
        <a-input v-model:value="form.nickName" placeholder="请输入昵称" />
      </a-form-item>
      
      <a-form-item label="密码" name="password" v-if="!formData.userId">
        <a-input-password v-model:value="form.password" placeholder="请输入密码" />
      </a-form-item>
      
      <a-form-item label="邮箱" name="email">
        <a-input v-model:value="form.email" placeholder="请输入邮箱" />
      </a-form-item>
      
      <a-form-item label="手机号" name="phonenumber">
        <a-input v-model:value="form.phonenumber" placeholder="请输入手机号" />
      </a-form-item>
      
      <a-form-item label="性别" name="sex">
        <a-radio-group v-model:value="form.sex">
          <a-radio :value="0">男</a-radio>
          <a-radio :value="1">女</a-radio>
          <a-radio :value="2">未知</a-radio>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="1">正常</a-radio>
          <a-radio :value="0">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item label="角色" name="roleIds">
        <a-select
          v-model:value="form.roleIds"
          placeholder="请选择角色"
          mode="multiple"
          style="width: 100%"
        >
          <a-select-option v-for="role in roleOptions" :key="role.roleId" :value="role.roleId">
            {{ role.roleName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="form.remark" placeholder="请输入备注" :rows="4" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import * as userApi from '@/api/user'
import * as roleApi from '@/api/role'
import type { SysUser } from '@/types/user'
import type { SysRole } from '@/types/role'

const props = defineProps<{
  visible: boolean
  formData: Partial<SysUser>
}>()

const emit = defineEmits(['update:visible', 'success'])

// 表单ref
const formRef = ref<FormInstance>()

// 表单数据
const form = reactive<any>({
  userId: '',
  userName: '',
  nickName: '',
  password: '',
  email: '',
  phonenumber: '',
  sex: 0,
  status: 1, // 默认正常状态
  roleIds: [],
  remark: ''
})

// 表单校验规则
const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phonenumber: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

// 加载状态
const confirmLoading = ref(false)

// 角色选项
const roleOptions = ref<SysRole[]>([])

// 监听表单数据变化
watch(
  () => props.formData,
  (val) => {
    if (val) {
      // 重置表单
      formRef.value?.resetFields()
      
      // 填充表单数据
      Object.keys(form).forEach(key => {
        if (key in val) {
          // @ts-ignore
          form[key] = val[key]
        }
      })
      
      // 如果是编辑模式，不需要密码
      if (val.userId) {
        form.password = undefined
      }
    }
  },
  { immediate: true, deep: true }
)

// 监听visible变化
watch(
  () => props.visible,
  (val) => {
    if (val) {
      // 获取角色列表
      getRoleList()
    }
  }
)

// 获取角色列表
const getRoleList = async () => {
  try {
    const res = await roleApi.getRoleList()
    roleOptions.value = res
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
}

// 确定
const handleOk = async () => {
  try {
    // 表单验证
    await formRef.value?.validate()
    
    confirmLoading.value = true
    
    // 构建请求数据
    const data = { ...form }
    
    // 调用API
    if (props.formData.userId) {
      await userApi.updateUser(data)
    } else {
      await userApi.addUser(data)
    }
    
    message.success(props.formData.userId ? '修改成功' : '新增成功')
    
    // 关闭对话框并通知父组件刷新
    emit('update:visible', false)
    emit('success')
  } catch (error) {
    console.error('提交表单失败:', error)
  } finally {
    confirmLoading.value = false
  }
}
</script>
